﻿using System;
using System.Linq;
using System.Windows.Forms;

namespace N2.Explorer
{
	static class ContentItemExtensions
	{
		public static TreeNode ToTreeNode(this ContentItem item)
		{
			return item.ToTreeNode(false);
		}

		public static TreeNode ToTreeNode(this ContentItem item, bool expandGrandChildren)
		{
			var _children =
				expandGrandChildren
					? item.GetChildren().Select(_item => _item.ToTreeNode(false)).ToArray()
					: new TreeNode[0];

			return new TreeNode(item.Title, _children) {
				Name = item.Name,
				Tag = item.ID,
			};
		}

		public static void Populate(
				this TreeNode node,
				Func<ContentItem, TreeNode, TreeNode> mutator)
		{
			if (0 == node.Nodes.Count && node.Tag is int) {
				var _parent = node.Parent;
				var _item = Context.Persister.Get((int)node.Tag);
				
				_parent.Nodes.Insert(
					node.Index,
					mutator(_item, _item.ToTreeNode(true)));
				
				node.Remove();
			}
		}
	}
}
